package com.zxp.utils.winEnvUtils;

import java.io.IOException;

/**
 * Utility class for modifying and adding Windows system environment variables.
 */
public class UsrEnvUtils {

    /**
     * Modifies an existing Windows system environment variable.
     *
     * @param variableName  The name of the variable to be modified.
     * @param variableValue The new value for the variable.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static void modifySystemEnvironmentVariable(String variableName, String variableValue)
            throws IOException, InterruptedException {
        // Build the setx command for modification
        String command = "setx " + variableName + " " + variableValue;

        // Create a ProcessBuilder object
        ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", command);

        // Start the process and wait for it to complete
        Process process = processBuilder.start();
        int exitCode = process.waitFor();

        // Check if the command was executed successfully
        if (exitCode != 0) {
            throw new RuntimeException("Failed to modify environment variable. Exit code: " + exitCode);
        }
    }

    /**
     * Adds a new Windows system environment variable.
     *
     * @param variableName  The name of the new variable.
     * @param variableValue The value for the new variable.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static void addSystemEnvironmentVariable(String variableName, String variableValue)
            throws IOException, InterruptedException {
        // Build the setx command for addition
        String command = "setx " + variableName + " " + variableValue;

        // Create a ProcessBuilder object
        ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", command);

        // Start the process and wait for it to complete
        Process process = processBuilder.start();
        int exitCode = process.waitFor();

        // Check if the command was executed successfully
        if (exitCode != 0) {
            throw new RuntimeException("Failed to add environment variable. Exit code: " + exitCode);
        }
    }

    public static void main(String[] args) {
        try {
            // Example: Modify an existing variable named MY_VARIABLE
            modifySystemEnvironmentVariable("MY_VARIABLE", "new_value");

            // Example: Add a new variable named NEW_VARIABLE
            addSystemEnvironmentVariable("NEW_VARIABLE", "new_value");

            System.out.println("Environment variables modified/added successfully.");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
